var actbill = require('../../model/clubshop_pro')

// var actclub_user = require('../../model/club_user')
Page({
  mixins: [require('../../../../xc/mixins/basicMixin')],
  /**
   * 页面的初始数据
   */
  data: {
    showedit:false,
    condition: {
      status: 0,
      type: 0,
      searchkey: ""
    },
    rightshow:false,
    themcolor: {},
    modellist: [],
    mode: "list",
    loading: true,
    actidx: 0,
    allpro: [{
        text: '全部商品',
        value: 0
      },
      {
        text: '平台商品',
        value: 1
      },
      {
        text: '自营商品',
        value: 2
      },
    ],
    prostatus: [{
        text: '商品状态',
        value: 0
      },
      {
        text: '在售中',
        value: 1
      },
      {
        text: '已下架',
        value: -1
      },
    ],
    rightnav: [{
        title: "商品类型",
        key:"allpro",
        keyname:"type",
        children: [{
            checked:true,
            text: '全部',
            value: 0
          },
          {
            checked:false,
            text: '平台商品',
            value: 1
          },
          {
            checked:false,
            text: '自营商品',
            value: 2
          },
        ]
      },
      {
        title: "商品状态",
        key:"prostatus",
        keyname:"status",
        children: [{
          checked:true,
            text: '全部',
            value: 0
          },
          {
            checked:false,
            text: '出售中',
            value: 1
          },
          {
            checked:false,
            text: '已下架',
            value: -1
          },
        ]
      }
    ],
    useplatformpro:-1,
  },
  changebtn(e){
  
    var val=e.detail;
    var that = this;
    actbill.changeuseplatform(val).then(res => {
      if (res["status"] == 1) {
        that.setData({
          useplatformpro:val
        })
        that.getpagelist(that,1)
      }
    })
  },
  //获取团长产品配置
  getclubinfor() {
    var that = this
    actbill.getclubinfor().then(res => {
      if (res["status"] == 1) {
        that.setData({
          level: res["obj"]['level'],
          bclass: res["obj"]['bclass'],
          sclass: res["obj"]['sclass'],
          clubid: res["obj"]['id'],
          useplatformpro: res["obj"]['useplatformpro']
        })
        that.getpagelist(that, 1)
      }
    })
  },
  rightchoose(e){
    var dataset=e.currentTarget.dataset;
    var index=dataset.index;
    var idx=dataset.idx;
    var clist=this.data.rightnav[index];
    var keyname=clist.keyname;
    var update={}
    for(var i in clist.children){
       if(i==idx){
        update['rightnav['+index+'].children['+i+'].checked']=true
       }else{
        update['rightnav['+index+'].children['+i+'].checked']=false
       }
    }


    var value=clist.children[idx].value
    update['condition.'+ keyname ]=value

    this.setData(update)


  },
  rightsearch(){
    this.onPullDownRefresh();
    this.rightshowclose()
  },
  rightshowclose(){
     this.setData({
       rightshow:!this.data.rightshow
     })
  },
  search(e) {
    var that = this;
    this.setData({
      'condition.searchkey': e.detail.value
    })
    this.onPullDownRefresh();
  },
  conchange(e) {

    var name = e.currentTarget.dataset.name;
    var coname = 'condition.' + name;
    this.setData({
      [coname]: e.detail
    })
    this.onPullDownRefresh();

  },
  onClickLeft: function () {

    wx.reLaunch({
      url: '/xc_lshop/club/manage/center',
    })

   
  },
  tabschange: function (ev) {

    var updatemodel = {};
    updatemodel["condition.status"] = ev.detail.name
    this.setData(updatemodel)
    this.onPullDownRefresh();

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var app = getApp();
    this.setData({
      StatusBar: app.globalData.StatusBar
    })
    // this.addpro()
  },
  addpro() {
    this.setData({
      showedit:true
    })
    this.selectComponent("#editform").show("add", 0);
  },
  saveform() {
   
  },
  xcloaddata: function (options, config) {
    var unit="￥"
    if(config.yihuo){
      if(config.yihuo.status==1){
        unit='∞';
        var allpro=this.data.allpro;
        allpro[2]['text']="社区商品"
        this.setData(
          {
            allpro:allpro
          }
        )
      }
      this.setData(
        {
          yihuoconfig:config.yihuo
        }
      )
    }
    this.setData(
      {
        unit:unit
      }
    )
    this.getclubinfor() 
    try {
      if (config.prothem) {
        var themcolor = config.prothem.themcolor.config
    
        this.setData({
          themcolor
        })
      }
    } catch (ex) {}
  },
  afterlogin() {
    var that = this;
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  exit() {
    this.setData({
      mode: "list"
    })
  },
  onChangeAll(e) {

    var update = {};
    // var checkids=[];
    var allchecked = this.data.allchecked;
    var modellist = this.data.modellist;
    var useplatformpro=this.data.useplatformpro;
    if (modellist.length > 0) {
      for (var i in modellist) {
        if((useplatformpro==1 && modellist[i].protype!=1) || useplatformpro==-1){
          if (allchecked) {
            update['modellist[' + i + '].checked'] = false
          } else {
            update['modellist[' + i + '].checked'] = true
          }
        }
       
      }
    }
    update['allchecked'] = e.detail

    this.setData(update);
  },
  groupop: function (ev) {
    var dataset = ev.currentTarget.dataset
    var idx = dataset.idx
    var that = this;

    switch (dataset.op) {
      case "add": {
        this.setData({
          showedit:true
        })
        this.selectComponent("#editform").show("add");
        break;
      }
      case "edit": {
        this.data.actidx = idx
     
        this.setData({
          showedit:true
        })
        this.selectComponent("#editform").show("edit", this.data.modellist[idx].id);
        break;
      }
      case "changestatus": {
        var item = this.data.modellist[idx];
        var that = this
        var status = -item.status
        actbill.changestatus(item.id, status).then(function (result) {
          if (result["status"] == 1) {
            var updatemodel = {};
            updatemodel['modellist[' + idx + '].status'] = status;
            that.setData(updatemodel)
            wx.showToast({
              title: (status == 1 ? "上架" : "下架") + '成功',
            })
          } else {
            wx.showToast({
              title: '操作失败',
            })
          }
        })
        break;
      }
      case "del": {
        var item = this.data.modellist[idx];
        wx.showModal({
          title: "删除",
          content: '确认删除' + '"' + item.name + '"',
          success: function (res) {
            if (res.cancel) {
              //取消删除
            } else {
              actbill.del(item.id).then(function (result) {
                if (result["status"] == 1) {
                  var modellist = that.data.modellist
                  modellist.splice(idx, 1)
                  that.setData({
                    modellist
                  })
                  wx.showToast({
                    title: '删除成功',
                  })
                } else {
                  wx.showToast({
                    title: '删除失败',
                  })
                }
              })
            }
          }
        })
        break;
      }
      case "select": {
        var updatemodel = {};
        updatemodel['modellist[' + idx + '].checked'] = !this.data.modellist[idx].checked;
        that.setData(updatemodel)
        break;
      }
      case "manage": {
        this.setData({
          mode: "edit"
        })
        break;
      }
      case "import": {
        this.selectComponent("#import").show();
        break;
      }
    }
  },

  // selectall(val){
  //   var modellist= this.data.modellist
  //   if(val==1||val===true){
  //     this.data.modellist[idx]["checked"] =true;
  //   }
  //   else
  //   {
  //     this.data.modellist[idx]["checked"] =false
  //   }
  //   this.setData({modellist}) 
  // },
  
  batchoperation(ev) {
    var that = this;
    var dataset = ev.currentTarget.dataset

    var ids = [];
    this.data.modellist.forEach(item => {
      if (item.checked) {
        ids.push(item.id)
      }

    })
    if (ids.length < 1) {
      wx.showModal({
        title: "请选择要操作的产品",
        content: "请选择要操作的产品",
        showCancel: false

      })
    } else {
      switch (dataset.op) {
        case "changestatus": {
          var val = dataset.val
          actbill.changestatus(ids.join(","), val).then(function (result) {
            if (result["status"] == 1) {
              var updatemodel = {};
              that.data.modellist.forEach((item, index) => {
                if (item.checked) {
                  updatemodel['modellist[' + index + '].status'] = val;
                }
              })
              that.setData(updatemodel)
              wx.showToast({
                title: (val == 1 ? "上架" : "下架") + '成功' + ids.length + "个",
              })
            } else {
              wx.showToast({
                title: '操作失败',
              })
            }
          })
          break;
        }

        case "del": {

          wx.showModal({
            title: "删除",
            content: '确认删除' + '"' + ids.length + '"产品',
            success: function (res) {
              if (res.cancel) {
                //取消删除
              } else {
                actbill.del(ids.join(",")).then(function (result) {
                  if (result["status"] == 1) {
                    var modellist = that.data.modellist
                    var newlist = modellist.filter(function (item) {

                      return item.checked


                    })

                    that.setData({
                      modellist: newlist
                    })
                    wx.showToast({
                      title: '删除成功',
                    })
                  } else {
                    wx.showToast({
                      title: '删除失败',
                    })
                  }
                })
              }
            }
          })
          break;
        }
      }
    }


  },
   
  getcondition() {
    var condition=this.data.condition;
    condition['useplatformpro']=this.data.useplatformpro;
    condition['shopid']=this.data.clubid;

 
    return condition;
  },
  editformchange(ev) {
    var data = ev.detail
    if (data.op == 'update') {
      var upatemodel = {};
      upatemodel["modellist[" + this.data.actidx + "]"] = data.model
      this.setData(upatemodel)
    } else if (data.op == 'add') {
      this.onPullDownRefresh();
    }
    this.setData({
      showedit:false
    })
  },

  getpagelist(that, rest, condition) {
    if (rest == 1) {
      that.setData({
        modellist:[]
      })
    }
    if(!condition){
      condition = this.getcondition();
    }
    actbill.offset(that, rest, condition).then(function (result) {
      var updatemodel = {};
      if ((result["code"] == "over" && result["obj"]) || result["code"] == "loadmore") {
        if (result["obj"]["modellist"].length < 1 && that.data.modellist.length < 1) {

        } else if (rest == 1) {
          updatemodel["modellist"] = result["obj"]["modellist"];
        } else {
          if (result["obj"]["modellist"].length > 0) {
            updatemodel["modellist"] = that.data.modellist.concat(result["obj"]["modellist"]);
          }
        }
      }

      wx.stopPullDownRefresh();
      that.setData(updatemodel);
    }, function () {

    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this
    that.getpagelist(that, 1)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this
    that.getpagelist(that, -1)
  },

  
})